<?php
namespace app\common\model;

class PatchModel extends BaseModel
{
    protected $name = 'patch'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /*读取器*/
    protected function getPatchTypeTextAttr($value, $data)
    {
        if ($data['patch_type'] == '102001') {
            return '单图碎片';
        }
        if ($data['patch_type'] == '102002') {
            return '多图碎片';
        }
        if ($data['patch_type'] == '102003') {
            return '代码碎片';
        }
        if ($data['patch_type'] == '102004') {
            return '富文本碎片';
        }
    }

    protected function getContentFormatAttr($value, $data)
    {
        if ($data['patch_type'] == '102001') {
            return json_decode($data['patch_content'], true);
        }
        if ($data['patch_type'] == '102002') {
            $arr = format_images_array($data['patch_content']);
            return $arr;
        }
        if ($data['patch_type'] == '102003') {
            $str = htmlspecialchars_decode($data['patch_content']);
            $str = stripslashes($str); //去除反斜杠
            return $str;
        }
        if ($data['patch_type'] == '102004') {
            $str = htmlspecialchars_decode($data['patch_content']);
            $str = stripslashes($str); //去除反斜杠
            return $str;
        }
    }

    /*修改器*/
    public function formatPatch($data)
    {
        $content = '';
        switch ($data['patch_type']) {
            case '102001':  //单图碎片
                $content = ['img' => $data['img'], 'url' => $data['url'], 'desc' => $data['desc']];
                $content = json_encode($content, true);
                break;
            case '102002': //多图碎片
                $content = $data['items'];
                break;
            case '102003':
                $content = $data['code_content'];
                break;
            case '102004':
                $content = $data['html_content'];
                break;
            default;
                break;
        }
        return $content;
    }

    /**
     * 碎片初始化
     * 将site_id为0且以site_开头得碎片复制到站点后台
     * @param $siteId
     * @return bool
     */
    public function initData($siteId)
    {
        if($siteId>0){
            $info = $this->where('site_id',$siteId)->where('patch_sn','like','site_%')->find();
            if(!$info){
                //碎片模板
                $patchList = $this->field('patch_id',true)
                    ->where('site_id',0)
                    ->where('patch_sn','like','site_%')
                    ->select()
                    ->toArray();
                $dataList = [];
                foreach ($patchList as $k=>$v){
                    $v['site_id'] = $siteId;
                    $dataList[] = $v;
                }
                $this->saveAll($dataList);
            }
        }
        return true;
    }
}




